<template>
  <div :id="smallType ? 'smallType' : 'largeType'" ref="attrConstraint" class="v-attrConstraint">
    <div :class="smallType ? '_smallType' : '_largeType'" class="_attrConstraint-container">
      <div class="g-jc-sb _header g-flex-0">
        <div class="g-ai-c">
          <!-- <img :src="selectedElement && selectedElement.iconPath" alt="" style="margin-right: 4px">
          <span style="font-size:12px; color: #000">
            {{type}}
          </span> -->
          <span style="font-size:12px; color: #000">约束</span>
        </div>
        <div class="g-ai-c">       
          <span class="_sort _img-btn" :class="{'_sort-active':sortActive}" @click="handleSort">
            <img src='statics/icons/app/textsort.png'/>
          </span>
        </div>   
      </div>
      <main>
        <a-table
          class="_table-area"
          rowKey="id"
          :rowClassName="rowClassName"
          :columns="columns"
          :scroll="{ y: scrollY }"
          :style="{width: '100%'}"
          :customRow="customRow"
          :data-source="sortData"
          :pagination="false"
          :locale="tablenodata"
          :bordered="true">
          <template slot="name" slot-scope="text, record">
            <div style="display: flex; align-items: center; height: 22px" @dblclick="currentEditId = record.id">
              <a-input 
                v-if="record.id === currentEditId" 
                v-model="record.cacheName"
                v-focus
                style="height: 20px; margin-left: -5px; padding-left: 4px;"
                @blur="updateName(record)"
                @pressEnter="handlePressEnter"/>
              <span v-else>{{text}}</span>
            </div>
          </template>
          <template slot="property" slot-scope="text, record">
            <m-property
              :property="record.property"
              :graphNode="record.graphNode"
              :isPropertyGroup="true"
            />
          </template>
        </a-table>
      </main>
    </div>
    <div class="g-ai-c _button-area">
      <a-button 
        :disabled="selectedElement && selectedElement.disabled"
        class="g-ai-c addButton" 
        @click="addConstraint">
        <img src='statics/icons/table/iconadd2.svg' width="14px"/>
        <span v-if="!smallType">创建</span>
      </a-button>
      <a-button class="g-ai-c" @click.stop="applyConstraint">
        <img src='statics/icons/app/iconuse.svg' width="14px"/>
        <span v-if="!smallType" style="margin-left: 0">应用</span>
      </a-button>
      <a-button :disabled="selectedRowKeys.length === 0" class="g-ai-c" @click="removeConstraint">
        <img src='statics/icons/app/icondisuse.svg' width="14px"/>
        <span v-if="!smallType">去用</span>
      </a-button>
    </div>
  </div>
</template>
<script>
import Property from './Property';
import { PropertyUtil } from './PropertyUtil';
import { graphHelper } from 'src/api/GraphHelper';
import { SysMLUtilHelper } from "src/api/sysml-imports";
import { actions, OpenCreateElementAction } from '@/pages/mxgraph/Actions';
import { selectValue } from '@/components/Attribute/modals/SelectValue.vue';

const columns = [
  {
    title: '名称',
    dataIndex: 'name',
    key: 'name',
    scopedSlots: { customRender: 'name' },
  },
  {
    title: '规范',
    dataIndex: 'property',
    key: 'property',
    scopedSlots: { customRender: 'property' },
  }
];

export default {
  name: 'attr-constraint',
  components: {
    'm-property': Property
  },
  directives: {
    focus: {
      //// 指令的定义
      inserted: function (el) {
        el.focus();
      },
    },
  },
  props: {
    property: Object, //// 当前选中元素的property
    smallType: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      columns: columns,
      sortActive: false,
      tableData: [],
      scrollY: 300,
      selectedRowKeys: [],
      constraintIds: new Set(),
      currentEditId: '',
      isAdd: false,
      tablenodata: {
        emptyText: '暂无数据'
      },
      type: '',
    };
  },
  computed: {
    selectedElement(){
      return app.selectedElement;
    },
    
    sortData() {
      let tableData = [...this.tableData];
      if (this.sortActive) {
        tableData.sort((a, b) => ('' + a.name).localeCompare(b.name));
      }
      return tableData;
    },
  },
  watch: {
    selectedElement: {
      handler(val) {
        const type = val.getTypeName();
        this.type = app.activeProject.configManager.getTypeNameConfig()[type]?.cnName || '';
        this.initData();
      },
      immediate: true
    },
    value: function (newVal, oldVal) {
      this.getColumns();
    },
  },
  created() {
    //// this.initData();
  },
  mounted() {
    //// if (this.smallType) {
    ////   const tableDom = document.querySelector('.v-workspace-attribute .ant-tabs-content');
    ////   this.scrollY = tableDom.offsetHeight - 28 - 23;
    //// }
    this.initClickEvent();
  },
  methods: {
    //// 初始化信息
    initData() {
      this.sortActive = false;
      this.selectedRowKeys = [];
      this.constraintIds = new Set();
      this.currentEditId = '';
      this.getData();
    },
    getData() {
      if (!this.selectedElement) {
        return;
      }
      const data = this.selectedElement.getApplyConstraint().toArray();
      const tableData = [];
      const constraintIds = [];
      data.forEach(model => {
        const currentData = {};
        const graphNode = graphHelper.getGraphNodeById(model.id, app.activeProjectId);
        currentData.name = graphNode.name;
        currentData.cacheName = graphNode.name;
        currentData.graphNode = graphNode;
        currentData.property = graphNode.getPropertyByPropertyName('规范定义');
        currentData.id = graphNode.id;
        tableData.push(currentData);
        constraintIds.push(graphNode.id);
      });
      this.tableData = tableData;
      this.constraintIds = new Set(constraintIds);
      //// console.log('data', data);
      this.$nextTick(this.setScrollBarStyle);
    },

    //// 新建约束
    addConstraint() {
      const menuItem = {
        icon: "statics/images/sysml/Constraint.svg",
        label: "约束",
        type: "",
        value: "Constraint"
      };
      const constraintNode = actions.getAction('openCreateElement').run(this.selectedElement, menuItem);
      this.selectedElement.applyConstraint(constraintNode.model);
      this.selectedRowKeys = [constraintNode.id];
      this.getData();
      this.$nextTick(() => {
        this.currentEditId = constraintNode.id;
      });
    },

    //// 删除约束
    removeConstraint() {
      const currentId = this.selectedRowKeys[0];
      const currentGraphNode = this.tableData.filter(node => node.id === currentId)[0].graphNode;
      this.selectedElement.removeApplyConstraint(currentGraphNode.model);
      this.selectedRowKeys = [];
      this.getData();
      if (this.currentEditId === currentId) {
        this.currentEditId = '';
      }
      this.$nextTick(this.setScrollBarStyle);
    },

    //// 应用约束
    applyConstraint() {
      selectValue.popup({
        isNodeSelectable: this.filterConstraint,
        shouldBeCut: this.shouldBeCut
      }).then(res => {
        const graphNode = res.graphNode;
        const result = this.selectedElement.applyConstraint(graphNode.model);
        this.getData();
      }).catch(e => {
        console.log(e);

      });
    },

    filterConstraint(graphNode) {
      if (graphNode.getTypeName() !== "Constraint") return false;
      if (this.constraintIds.has(graphNode.id)) return false;
      if (graphNode.id === this.selectedElement.id)  return false;
      return true;
    },

    shouldBeCut(graphNode) {
      if (graphNode.getTypeName() === "Constraint") {
        return true;
      } else {
        return false;
      }
    },

    //// 设置滚动条样式
    setScrollBarStyle() {
      const table = this.$refs.attrConstraint;
      const tableBody = table.querySelector('.ant-table-body');
      const tableHeader = table.querySelector('.ant-table-header');
      const height = tableBody.offsetHeight;
      //// console.log('height', height, this.scrollY, tableBody);
      if (height >= this.scrollY) {
        tableHeader.style.marginRight = '-1px';
      } else {
        tableHeader.style.marginRight = '-12px';
      }
      if (this.isAdd) {
        tableBody.scrollTop = table.querySelector('.ant-table-tbody').offsetHeight; //// 滚到最底部
      }
    },

    handleSort() {
      this.sortActive = !this.sortActive;
    },

    rowClassName(record) {
      if (record.id === this.selectedRowKeys[0]) {
        return 'selected';
      } else {
        return '';
      }
    },

    //// 自定义行
    customRow(record) {
      //// console.log(record, 'record');
      const graphNode = graphHelper.getGraphNodeById(record.id, app.activeProjectId);
      return {
        on: {
          click: (event) => {
            if (graphNode.disabled) return; 
            this.selectedRowKeys = [record.id];
          },
        }
      };
    },

    //// 重置点击后的选中效果，点击行以外的地方取消选中
    initClickEvent() {
      const table = this.$refs.attrConstraint;
      const tableArea = table.querySelector('._table-area');
      const main = table.querySelector('main');
      this.selectedRowKeys = [];
      tableArea.onclick = function (e) {
        e.stopPropagation();
      };
      main.onclick = () => {
        this.selectedRowKeys = [];
      };
    },

    handlePressEnter(e) {
      e.target.blur();
    },

    updateName(record) {
      const graphNode = record.graphNode;
      if (record.cacheName !== record.name) {
        const property = graphNode.getPropertyByPropertyName('名称');
        PropertyUtil.updateRow(record.cacheName, property, graphNode);
        const currentName = graphNode.name;
        if (currentName === record.cacheName) { //// 修改成功
          record.name = record.cacheName;
        } else { //// 修改失败
          record.cacheName = record.name;
        } 
      }     
      this.currentEditId = '';
    }
  }
};
</script>
<style lang="scss">
.v-attrConstraint {
  padding: 8px;
  padding-bottom: 0;
  height: 100%;
  ::-webkit-scrollbar {
    width: 6px;
  }
  ._attrConstraint-container {
    height: calc(100% - 50px);
    padding-bottom: 10px;
    &._largeType {
      border-top: 1px solid #E4E3E3;
      border-bottom: 0;
    }
  }
  ._button-area {
    height: 50px;
    border-top: 1px solid #E4E3E3;
    margin: 0 -8px;
    padding-left: 8px;
      button {
        width: 64px;
        height: 32px;
        padding: 0 8px;
        border-color: #D9D9D9;
        border-radius: 0px;
        span {
          line-height: 16px;
        }
        & + button {
          margin-left: 8px;
        }
        img {
          margin-right: 3px;
        }
      }
    }
	._row {
		line-height: 20px;
    ._readonly{
      color: rgba(0,0,0,.45);
    }
	._col-label {
		line-height: 20px;
		flex: 0 0 96px;
		width: 96px;
		border-right: 1px solid #eee;
		color: black;
		padding: 5px;
		font-size: 12px;
	}
	._col-value {
		line-height: 20px;
		flex:1 1 100px;
		width: 100px;
		padding: 5px;
		border: 1px solid transparent;
	}
	&._selected {
		._col-label {
			background: #3483b8;
			//// border-right: 1px solid #3483b8;
			color: white;
		}
      ._col-value{
        box-sizing: border-box;
        border: 1px solid #1890FF;
      }

	}
  }
._header {
    padding:4px 10px ;
    background:#D4EBF8;
    border-left: 1px solid #E4E3E3;
    border-right: 1px solid #E4E3E3;
    height: 30px;
    
	}
	._sort {
    border: 1px solid #D4EBF8;
    vertical-align: middle;
		&._sort-active {
		  background: linear-gradient(180deg, #B9E3FF 0%, #47B3FF 55%, #80C8FE 100%);
      border: 1px solid #B1CEE2;
		}
	}
	._img-btn {
		display: inline-block;
		box-sizing: border-box;
		cursor: pointer;
		img {
			display: block;
			height: 14px;
			width: 14px;
		}
		&:hover {
      background: linear-gradient(180deg, #E7F5FE 0%, #B0DEFF 65%, #B2DDFD 100%);
      border: 1px solid #B1CEE2;
		}
		&:active {
      background: linear-gradient(180deg, #B9E3FF 0%, #47B3FF 55%, #80C8FE 100%);
      border: 1px solid #B1CEE2;
		}
  }
  main {
    ._table-area {
      .ant-table-header {
        //// overflow: unset !important;
        table {
          border-top: 0;
          border-radius: 0;
        }
        &::-webkit-scrollbar {
          border: 0 !important;
        }
        th {
          border-radius: 0;
          &:last-of-type {
            border-right-color: #E4E3E3 !important;
          }
        }
      }
      .hide-row {
        display: none;
      }
      .ant-table-body {
        overflow-y: auto !important;
        overflow-x: auto !important;
        &::-webkit-scrollbar {
          width: 12px;
        }
      }
      table {
        border-color: #E4E3E3;
        font-size: 12px;
      }
      tr {
        td {
          transition: unset;
          &:last-of-type {
            border-top: 1px solid #fff;
          }
        }
        &:hover {
          td {
            background-color: #fff !important;
          }
        }
        &.selected {         
          td {
            border-color: #3483B8;
            &:first-of-type {
              border-top: 1px solid #3483B8;
              background-color: #3483B8 !important;
              color: #fff;
            }
            &:last-of-type {
            border-top: 1px solid #3483B8;
          }
          }
        }
      }
      tr th {
        padding: 5px 10px;
        border-color: #E4E3E3;
      }
      tr td {
        padding: 2px 10px;
        border-color: #E4E3E3;
      }
      ._col-value {
        padding: 0;
        height: 22px;
        ._img-btn {
          top: 2px !important;
        }
      }
      .ant-select-selection--single {
        height: 20px;
        .ant-select-selection__rendered {
          line-height: 18px;
        }
      }
      .v-simple-input {
        height: 20px !important;
        min-height: 20px !important; 
      }
      .v-attr-compounded-input {
        height: 20px;
        line-height: 20px;
        .ant-input-sm {
          height: 20px;
        }
      }
      .v-simple-input {
        height: 20px;
        padding-bottom: 0;
        padding-top: 0;
        min-height: 20px;
      }
    }
  }
  &#smallType {
    background-color: #fff;
    margin-right: 3px;
    ._header {
      position: relative;
      z-index: 1;
      height: 28px;
      background: #D4EBF8;
      border-bottom: 1px solid #B1CEE2;
      padding-left: 11px;
      padding-right: 17px;
      ._sort {
        border-color: #D4EBF8;
      }
      ._button-area {
        button {
          padding: 0;
          border: 0;
          background: #D4EBF8;
          img {
            margin-right: 0;
          }
        }
        ._menu-area {
          left: -76px;
        }
      }
    }
    main {
      margin: 0;
      margin-top: -1px;
      height: calc(100% - 30px);
      ._table-area {
        th, td {
          border-color: #F0F0F0;
        }
        tr, th {
          padding-top: 2px;
          padding-bottom: 2px;
        }
      }
    }
  }
}
</style>
